﻿using HZYProject.Core.Repositories;
using HZYProject.Data;
using HZYProject.Domain;
using HZYProject.Service.CollegeServices;
using HZYProject.Service.StudentServices;
using HZYProject.Web.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HZYProject.Web.Controllers
{
    /// <summary>
    /// 学生管理
    /// </summary>
    [Route("Student")]
    public class StudentController : Controller
    {
        private readonly IRepository<Student, Guid> _repository;
        private readonly IStudentService _studentService;
        private readonly IRepository<Colleges, Guid> _collegesRepository;
        private readonly IRepository<Class, Guid> _classRepository;
        private readonly IRepository<User, Guid> _userRepository;
        private readonly HZYProjectDbContext _dbContext;

        public StudentController(IRepository<Student, Guid> repository, IStudentService studentService, IRepository<Colleges, Guid> collegesRepository, IRepository<Class, Guid> classRepository,IRepository<User, Guid> userRepository, HZYProjectDbContext dbContext)
        {
            _repository = repository;
            _studentService = studentService;
            _collegesRepository = collegesRepository;
            _classRepository = classRepository;
            _userRepository = userRepository;
            _dbContext = dbContext;
        }

        #region 首页分页查询
        [HttpGet("")]
        public IActionResult Index()
        {
            var list = _collegesRepository.GetAllList();
            ViewBag.Names = _classRepository.GetAllList();
            return View(list);
        }
        [HttpPost("")]
        public async Task<IActionResult> Index(UIStudent c)
        {
            try
            {
                GetStudentInput input = new GetStudentInput { ID = c.StudentID, Name = c.RealName, CID = c.CollegesId };
                var data = await _studentService.GetPaginatedResult(input);
                var list = data.Data.Select(x => new UIStudent
                {
                    StudentID = x.StudentID,
                    WXOpenID = x.WXOpenID,
                    IdNo = x.IdNo,
                    PassWord = x.PassWord,
                    CollegesId = x.CollegesId,
                    RealName = x.RealName,
                    Sex = x.Sex,
                    Mphone = x.Mphone,
                    Email = x.Email,
                    CreateTime = x.CreateTime,
                    Status = x.Status,
                    CollegeName = x.Colleges.Name
                });
                return Json(new { code = 0, msg = "", data = list, count = data.TotalCount });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "查询出错:" + ex.Message, data = new List<UIStudent>(), count = 0 });
            }
        }
        #endregion

        #region 添加
        [HttpGet("add")]
        public IActionResult Add()
        {
            var list = _classRepository.GetAllList();
            return View(list);
        }
        [HttpPost("add")]
        public IActionResult Add(UStudent stu)
        {
            try
            {
                var n = User.Identity.Name;
                var user = _userRepository.FirstOrDefault(x => x.UserName == n);
                var pwd = "~" + stu.IdNo.Substring(12, 6);
                Student s = new Student();
                s.StudentID = Guid.NewGuid();
                s.RealName = stu.RealName;
                s.PassWord = pwd;
                s.CollegesId = user.CollegesID;
                s.IdNo = stu.IdNo;
                s.Sex = stu.Sex;
                s.Mphone = stu.Mphone;
                s.Email = stu.Email;
                s.CreateTime = DateTime.Now;
                s.Status = stu.Status;
                //s.Classes.Clear();
                //foreach (var item in stu.ClassID)
                //{
                //    s.Classes.Add(_classRepository.FirstOrDefault(x => x.ClassID == item));
                //}
                //_dbContext.Students.Add(s);
                //_dbContext.SaveChanges();
                _repository.Insert(s);
                return Json(new { success = true, msg = "添加成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 修改
        [HttpGet("edit")]
        public IActionResult Edit(Guid id)
        {
            var obj = _repository.FirstOrDefault(x => x.StudentID == id);
            ViewBag.ClassNames = _classRepository.GetAllList();
            return View(obj);
        }
        [HttpPost("edit")]
        public IActionResult Edit(UIStudent stu)
        {
            try
            {
                if (ModelState.IsValid)//obj在形成对象时，是否全部符合注解中的规定
                {
                    var obj = _repository.FirstOrDefault(x => x.StudentID == stu.StudentID);
                    obj.RealName = stu.RealName;
                    obj.Sex = stu.Sex;
                    obj.Mphone = stu.Mphone;
                    obj.Email = stu.Email;
                    obj.Status = stu.Status;
                    obj.Classes.Clear();
                    foreach (var item in stu.ClassID)
                    {
                        obj.Classes.Add(_classRepository.FirstOrDefault(x => x.ClassID == item));
                    }
                    _repository.Update(obj);
                    return Json(new { success = true, msg = "修改成功" });
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    int i = 1;
                    foreach (var v in ModelState.Values)
                    {
                        foreach (var p in v.Errors)
                        {
                            sb.AppendFormat("{0}-{1};", i++, p.ErrorMessage);
                        }
                    }
                    return Json(new { success = false, msg = "服务端验证未通过," + sb });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }

        }
        #endregion

        #region 删除
        [HttpPost("remove/{id}")]
        public IActionResult Del(Guid id)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.StudentID == id);
                _repository.Delete(obj);
                return Json(new { success = true, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

        #region 解锁
        [HttpPost("unlock/{id}")]
        public IActionResult UnLock(Guid id)
        {
            try
            {
                var obj = _repository.FirstOrDefault(x => x.StudentID == id);
                obj.Status = (StuStatus)1;
                _repository.Update(obj);
                return Json(new { success = true, msg = "解锁成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = ex.Message });
            }
        }
        #endregion

    }
}
